package core.input;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JFileChooser;

import data.map.TerrainMap;

public class DefaultModeActionListener implements ActionListener{
	
	private TerrainMap map;
	private String mapDirectory = "maps/";
	private JFileChooser jf;
	
	public DefaultModeActionListener(TerrainMap map){
		this.map = map;
		jf = new JFileChooser();
		jf.setCurrentDirectory(new File(mapDirectory));
		File f = new File(mapDirectory);
		if(!f.exists()){
			f.mkdirs();
		}
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();

		if (command.equals("Neu")) {
			map.rerollMap();
		} else if (command.equals("Speichern")) {
			int i = jf.showSaveDialog(null);
			if (i == 0) {
				String str = map.getMapAsString();

				try {
					PrintWriter w = new PrintWriter(jf.getSelectedFile()
							.getPath());
					w.println(str);
					w.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				;
			}
		} else if (command.equals("Laden")) {
			int i = jf.showOpenDialog(null);
			if (i == 0) {
				try {
					String str = new BufferedReader(new FileReader(
							jf.getSelectedFile())).readLine();
					map.buildFromString(str);
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}

		}
		
	}

}
